package com.bestcem.xm.award.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.xuyanwu.spring.file.storage.FileInfo;
import com.alibaba.fastjson.JSON;
import com.bestcem.bp.grpc.v1.base.Code;
import com.bestcem.bp.pay.grpc.v1.services.ActivityInfo;
import com.bestcem.bp.pay.grpc.v1.services.GetActivityResponse;
import com.bestcem.xm.award.constant.Constants;
import com.bestcem.xm.award.controller.convert.AwardConvert;
import com.bestcem.xm.award.controller.convert.WinDataConvert;
import com.bestcem.xm.award.controller.dto.AwardListDTO;
import com.bestcem.xm.award.controller.param.award.*;
import com.bestcem.xm.award.controller.vo.award.*;
import com.bestcem.xm.award.enums.AwardStatusEnum;
import com.bestcem.xm.award.enums.AwardTypeEnum;
import com.bestcem.xm.award.grpc.client.ActivityGrpcService;
import com.bestcem.xm.award.grpc.client.AwardBaseUserGrpcService;
import com.bestcem.xm.award.grpc.service.param.award.DeleteAttachmentParam;
import com.bestcem.xm.award.grpc.service.param.award.ListAwardsLevelNamesParam;
import com.bestcem.xm.award.grpc.service.param.draw.PageParam;
import com.bestcem.xm.award.service.AwardStatsService;
import com.bestcem.xm.award.service.bo.award.AwardAwardBO;
import com.bestcem.xm.award.service.dto.AwardDataDTO;
import com.bestcem.xm.award.service.dto.awardaward.*;
import com.bestcem.xm.award.service.dto.draw.ExportWinnerDetailDTO;
import com.bestcem.xm.award.service.impl.AwardDispatcher;
import com.bestcem.xm.common.core.constant.RegTypes;
import com.bestcem.xm.common.core.constant.ReqErrorCodeConstants;
import com.bestcem.xm.common.core.constant.ResourceErrorCodeConstants;
import com.bestcem.xm.common.core.domain.web.PageResultDTO;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.common.core.uitls.EnumUtil;
import com.bestcem.xm.common.core.uitls.GRpcUtil;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.component.security.dto.TokenDTO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 奖励基本操作controller
 *
 * @author sh.pei <sh.pei@idiaoyan.com>
 * @version v3.0
 * @date 2021/8/17 16:37
 */
@Slf4j
@RestController
@RequestMapping(value = "/award/v3", produces = MediaType.APPLICATION_JSON_VALUE)
public class AwardAwardController {
    @Resource
    private ActivityGrpcService activityGrpcService;

    @Resource
    private AwardDispatcher awardAwardService;

    @Autowired
    private AwardBaseUserGrpcService awardBaseUserGrpcService;

    @Autowired
    private AwardStatsService awardStatsService;


    /**
     * 获取红包活动总金额
     *
     * @param activityId 红包活动id
     * @return 红包活动总金额
     */
    @ApiOperation(value = "获取红包活动总金额")
    @GetMapping(value = "/award/{id}")
    public XmResultJson<GetActivityAmountVO> getActivityAmount(@ApiParam(value = "红包活动id", required = true)
                                                               @PathVariable(value = "id") String activityId) {
        // 校验是否有活动id
        if (StrUtil.isEmpty(activityId)) {
            return XmResultJson.fail(ReqErrorCodeConstants.PARAM_LOST, "没有活动id");
        }

        // 前端传参格式校验
        if (!Pattern.matches(RegTypes.OBJECT_ID, activityId)) {
            return XmResultJson.fail(5, "活动id格式错误");
        }

        // 调用钱包金额
        GetActivityResponse getActivityResponse = activityGrpcService.getActivity(activityId);
        if (getActivityResponse.getStatus().getCodeValue() == Code.OK_VALUE) {
            Optional<Integer> amount = Optional.of(getActivityResponse.getActivity()).map(ActivityInfo::getAmount);
            if (amount.isPresent()) {
                GetActivityAmountVO getActivityAmountVO = new GetActivityAmountVO(amount.get());
                return XmResultJson.success(getActivityAmountVO);
            } else {
                return XmResultJson.fail(ResourceErrorCodeConstants.NOT_FOUND, "红包活动金额未查到");
            }
        }
        log.error("[award] activityGrpcService调用失败,code:{},msg:{}", getActivityResponse.getStatus().getCode(), getActivityResponse.getStatus().getMessage());
        return XmResultJson.fail(ResourceErrorCodeConstants.THIRD_PART, "activityGrpcService调用失败");
    }

    /**
     * 定制奖励删除附件
     *
     * @param attachmentId 附件id
     * @param awardId      奖励id
     * @return 每次只删除一条，所以返回deleteCount=1
     * @author jie.yao <jie.yao@idiaoyan.com>
     * @date 2018/8/18 14:32
     */
    @DeleteMapping("/award/attachments/{id}")
    public XmResultJson<DeleteAttachmentVO> deleteAttachment(@PathVariable(value = "id") String attachmentId,
                                                             @RequestParam(value = "award_id", required = false) String awardId) {
        if (!ObjectId.isValid(attachmentId)) {
            return XmResultJson.fail(ReqErrorCodeConstants.PARAM_LOST, "id is required");
        }
        // 入参
        DeleteAttachmentQuery query = new DeleteAttachmentQuery(attachmentId, awardId);
        // service层入参
        DeleteAttachmentParam param = query.getDeleteAttachmentParam();
        // 校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(ReqErrorCodeConstants.PARAM_FORMAT, violation.getMessage());
        }
        ServiceResult<String> serviceResult = awardAwardService.deleteAttachment(param);
        if (serviceResult.isSuccess()) {
            // 每次只删除一条，所以返回deleteCount=1
            DeleteAttachmentVO deleteAttachmentVO = new DeleteAttachmentVO(Constants.ONE);
            return XmResultJson.success(deleteAttachmentVO);
        } else {
            return XmResultJson.fail(1, serviceResult.getMsg());
        }
    }

    /**
     * 定制奖励上传附件
     *
     * @param file 附件
     * @return UploadAttachmentVO
     * @author jie.yao <jie.yao@idiaoyan.com>
     * @date 2018/8/18 16:09
     */
    @PostMapping("/award/attachments")
    public XmResultJson<UploadAttachmentVO> uploadAttachment(@RequestParam("attachment") MultipartFile file) {
        if (Validator.isNull(file)) {
            return XmResultJson.fail(ReqErrorCodeConstants.PARAM_LOST, ":attachment is required");
        }
        ServiceResult<FileInfo> serviceResult = awardAwardService.uploadAttachment(file);
        if (serviceResult.isSuccess()) {
            FileInfo fileInfo = serviceResult.getData();
            UploadAttachmentVO uploadAttachmentVO = new UploadAttachmentVO(fileInfo.getId(), fileInfo.getUrl(),
                    fileInfo.getFilename(), fileInfo.getCreateTime());
            return XmResultJson.success(uploadAttachmentVO);
        } else {
            return XmResultJson.fail(serviceResult.getErrorData() != null ? serviceResult.getErrorData().getCode() : 1, serviceResult.getMsg());
        }
    }

    /**
     * 上传兑奖码文件
     *
     * @param file 兑奖码文件
     * @return 兑奖码信息
     * @author jie.yao <jie.yao@idiaoyan.com>
     * @date 2018/8/18 17:50
     */
    @PostMapping("/award/draw/code/file")
    public XmResultJson<ImportDrawCodesVO> importDrawCodes(@RequestParam("file") MultipartFile file) {
        if (Validator.isNull(file)) {
            return XmResultJson.fail(ReqErrorCodeConstants.PARAM_LOST, ":excel file is lost");
        }
        ServiceResult<List<ExportWinnerDetailDTO>> serviceResult = awardAwardService.importDrawCodesLessThanTenThousand(file);
        if (serviceResult.isSuccess()) {
            ImportDrawCodesVO importDrawCodesVO = AwardConvert.importDrawCodesConversion(serviceResult.getData());
            return XmResultJson.success(importDrawCodesVO);
        } else {
            return XmResultJson.fail(serviceResult.getErrorData() != null ? serviceResult.getErrorData().getCode() : 1, serviceResult.getMsg());
        }
    }

    /**
     * 创建奖励
     *
     * @param createAwardParam 请求参数
     * @param request          请求
     * @return 创建结果
     */
    @PostMapping(value = "/award")
    public XmResultJson<CreateAwardVO> createAward(@RequestBody CreateAwardParam createAwardParam, HttpServletRequest request) {
        // 参数转换
        AwardAwardBO awardAwardBO = AwardConvert.awardDTOToAwardAward(createAwardParam.getAward());
        if (log.isInfoEnabled()) {
            log.info("[award] 创建奖励，奖励参数转换，请求参数{}，转换后参数{}", JSON.toJSONString(createAwardParam.getAward()), JSON.toJSON(awardAwardBO));
        }

        // token获取orgId

        String orgId = SecurityContextHolder.getOrgId();
        if (log.isInfoEnabled()) {
            log.info("[award] 从token里获取orgId:{}", orgId);
        }
        awardAwardBO.setOrgId(orgId);


        CreateAwardDTO serviceParam = new CreateAwardDTO();
        serviceParam.setAwardAward(awardAwardBO);
        serviceParam.setWinData(WinDataConvert.windataDTOToWinDataBO(createAwardParam.getWinData()));

        // 红包奖励准备好钱包id和用户id和用户姓名，之后请求钱包服务用到
        if (Objects.equals(awardAwardBO.getTType(), AwardTypeEnum.REDPACKET.getIndex())) {
            // 获取walletId
            ServiceResult<String> walletIdResult = awardBaseUserGrpcService.getWalletId(orgId);
            log.info("walletIdResult:" + JSON.toJSONString(walletIdResult));
            if (!walletIdResult.isSuccess()) {
                return XmResultJson.fail(walletIdResult.getErrorData(), walletIdResult.getMsg());
            }
            String walletId = walletIdResult.getData();

            // token获取用户id

            TokenDTO tokenDTO = SecurityContextHolder.getToken();
            String userId = tokenDTO.getUserId();
            String userName = tokenDTO.getRealName();
            serviceParam.setWalletId(walletId);
            serviceParam.setUserId(userId);
            serviceParam.setUserName(userName);
        }
        //调用业务层结构
        ServiceResult<String> serviceResult = awardAwardService.createAward(serviceParam);
        if (serviceResult.isSuccess()) {
            CreateAwardVO createAwardVO = new CreateAwardVO();
            createAwardVO.setId(serviceResult.getData());
            return XmResultJson.success(createAwardVO);
        } else {
            return XmResultJson.fail(serviceResult.getErrorData(), serviceResult.getMsg());
        }
    }

    /**
     * 修改奖励
     *
     * @param updateAwardParam 请求参数
     * @param request          请求参数
     * @return 修改结果
     */
    @PutMapping(value = "/award")
    public XmResultJson<UpdateAwardVO> updateAward(@RequestBody UpdateAwardParam updateAwardParam, HttpServletRequest request) {
        AwardAwardBO awardAwardBO = AwardConvert.awardDTOToAwardAward(updateAwardParam.getAward());
        if (log.isInfoEnabled()) {
            log.info("[award] 修改奖励，奖励参数转换，请求参数{}，转换后参数{}", JSON.toJSONString(updateAwardParam.getAward()), JSON.toJSON(awardAwardBO));
        }

        // token获取orgId

        String orgId = SecurityContextHolder.getOrgId();
        if (log.isInfoEnabled()) {
            log.info("[award] 从token里获取orgId:{}", orgId);
        }
        awardAwardBO.setOrgId(orgId);


        UpdateAwardDTO serviceParam = new UpdateAwardDTO();
        serviceParam.setAwardAward(awardAwardBO);
        serviceParam.setWinData(WinDataConvert.windataDTOToWinDataBO(updateAwardParam.getWinData()));

        // 红包奖励准备好钱包id和用户id和用户姓名，之后请求钱包服务用到
        if (Objects.equals(awardAwardBO.getTType(), AwardTypeEnum.REDPACKET.getIndex())) {
            // 获取walletId
            ServiceResult<String> walletIdResult = awardBaseUserGrpcService.getWalletId(orgId);
            if (!walletIdResult.isSuccess()) {
                return XmResultJson.fail(walletIdResult.getErrorData(), walletIdResult.getMsg());
            }
            String walletId = walletIdResult.getData();

            // token获取用户id

            TokenDTO tokenDTO = SecurityContextHolder.getToken();
            String userId = tokenDTO.getUserId();
            String userName = tokenDTO.getRealName();
            serviceParam.setWalletId(walletId);
            serviceParam.setUserId(userId);
            serviceParam.setUserName(userName);
        }

        ServiceResult<String> serviceResult = awardAwardService.updateAward(serviceParam);
        if (serviceResult.isSuccess()) {
            UpdateAwardVO updateAwardVO = new UpdateAwardVO();
            updateAwardVO.setId(serviceResult.getData());
            return XmResultJson.success(updateAwardVO);
        } else {
            return XmResultJson.fail(serviceResult.getErrorData(), serviceResult.getMsg());
        }
    }

    /**
     * 查询奖励
     *
     * @param id        奖励id
     * @param page      分页
     * @param size      每页大小
     * @param projectId 项目id
     * @param orderBy   排序方式
     * @param types     奖励类型
     * @param statuses  奖励状态
     * @param firstId   排在首位的奖励id
     * @param request   请求参数
     * @return 查询结果
     */
    @GetMapping(value = "/award")
    public XmResultJson<GetAwardVO> getAward(@RequestParam(value = "id", required = false) String id,
                                             @RequestParam(value = "page", required = false) Integer page,
                                             @RequestParam(value = "size", required = false) Integer size,
                                             @RequestParam(value = "project_id", required = false) String projectId,
                                             @RequestParam(value = "order_by", required = false) String orderBy,
                                             @RequestParam(value = "type", required = false) List<Integer> types,
                                             @RequestParam(value = "statuses", required = false) List<Integer> statuses,
                                             @RequestParam(value = "first_id", required = false) String firstId, HttpServletRequest request) {
        // 有id, 查询单个奖励
        if (StrUtil.isNotEmpty(id)) {
            GetAwardDTO serviceGetAwardDTO = new GetAwardDTO();
            serviceGetAwardDTO.setNeedWin(true);
            serviceGetAwardDTO.setId(id);
            ServiceResult<AwardDataDTO> serviceGetResult = awardAwardService.getAward(serviceGetAwardDTO);
            if (serviceGetResult.isSuccess()) {
                GetAwardVO getAwardVO = new GetAwardVO();
                getAwardVO.setAward(AwardConvert.awardAwardToAwardDTO(serviceGetResult.getData().getAward()));
                getAwardVO.setWinData(WinDataConvert.winDataToWinDataDTO(serviceGetResult.getData().getWinData()));
                return XmResultJson.success(getAwardVO);
            } else {
                return XmResultJson.fail(serviceGetResult.getErrorData(), serviceGetResult.getMsg());
            }

        }
        // 查询列表
        else {
            // token获取公司id

            String orgId = SecurityContextHolder.getOrgId();
            if (log.isInfoEnabled()) {
                log.info("[award] 从token里获取orgId:{}", orgId);
            }
            if (StrUtil.isEmpty(projectId)) {
                return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST, ":project_id is required");
            }
            if (StrUtil.isEmpty(orderBy)) {
                orderBy = ListPageAwardDTO.ORDER_FINISH_LAST_THEN_CREATE_FIRST;
            }
            if (CollectionUtil.isNotEmpty(types)) {
                for (Integer type : types) {
                    if (EnumUtil.getEnumByIndex(AwardTypeEnum.class, type) == null) {
                        return XmResultJson.fail(ReqErrorCodeEnum.PARAM_RANGE, "The \"type\" not allowed !");
                    }
                }
                // 新老抽奖兼容
                if (types.contains(AwardTypeEnum.DRAW.getIndex())) {
                    if (!types.contains(AwardTypeEnum.NEW_DRAW.getIndex())) {
                        types.add(AwardTypeEnum.NEW_DRAW.getIndex());
                    }
                } else if (types.contains(AwardTypeEnum.NEW_DRAW.getIndex())) {
                    if (!types.contains(AwardTypeEnum.DRAW.getIndex())) {
                        types.add(AwardTypeEnum.DRAW.getIndex());
                    }
                }

            }
            if (CollectionUtil.isNotEmpty(statuses)) {
                for (Integer status : statuses) {
                    if (EnumUtil.getEnumByIndex(AwardStatusEnum.class, status) == null) {
                        return XmResultJson.fail(ReqErrorCodeEnum.PARAM_RANGE, "The \"status\" not allowed !");
                    }
                }
            }
            ListPageAwardDTO listPageAwardDTO = new ListPageAwardDTO();
            listPageAwardDTO.setOrgId(orgId);
            listPageAwardDTO.setProjectId(projectId);
            listPageAwardDTO.setFirstId(firstId);
            listPageAwardDTO.setTTypes(types);
            listPageAwardDTO.setStatuses(statuses);
            listPageAwardDTO.setPaging(true);
            PageParam pageParam = new PageParam();
            pageParam.setPage(page == null ? 1 : page);
            pageParam.setSize(size == null ? 10 : size);
            listPageAwardDTO.setPageParam(pageParam);
            listPageAwardDTO.setOrderBy(orderBy);
            if (log.isInfoEnabled()) {
                log.info("[award] 列表查询奖励请求参数{}", JSON.toJSONString(listPageAwardDTO));
            }
            ServiceResult<PageResultDTO<AwardAwardBO>> serviceResult = awardAwardService.listPageAward(listPageAwardDTO);

            if (serviceResult.isSuccess()) {
                GetAwardVO getAwardVO = new GetAwardVO();
                getAwardVO.setPage(pageParam.getPage());
                getAwardVO.setSize(pageParam.getSize());
                Long total = serviceResult.getData().getTotal();
                if (total != null) {
                    getAwardVO.setTotal(Math.toIntExact(total));
                }
                List<AwardAwardBO> data = serviceResult.getData().getData();
                if (CollectionUtil.isNotEmpty(data)) {
                    data.stream().forEach(awardAward -> {
                        AwardListDTO awardListDTO = new AwardListDTO();
                        awardListDTO.setType(awardAward.getTType());
                        awardListDTO.setStatus(awardAward.getStatus());
                        awardListDTO.setName(awardAward.getName());
                        awardListDTO.setId(awardAward.getId());
                        awardListDTO.setCreateTime(DateUtil.format(com.bestcem.xm.common.core.uitls.DateUtil.getDate(awardAward.getCreatedDate()), Constants.DATE_PATTERN));
                        if (awardAward.getBasic() != null) {
                            AwardAwardBO.Basic basic = awardAward.getBasic();
                            if (Objects.nonNull(basic.getStartTime())) {
                                awardListDTO.setStartTime(DateUtil.format(com.bestcem.xm.common.core.uitls.DateUtil.getDate(basic.getStartTime()), Constants.DATE_PATTERN));
                            }
                            if (Objects.nonNull(basic.getStopTime())) {
                                awardListDTO.setEndTime(DateUtil.format(com.bestcem.xm.common.core.uitls.DateUtil.getDate(basic.getStopTime()), Constants.DATE_PATTERN));
                            }
                        }
                        getAwardVO.addAwardListDTO(awardListDTO);
                    });

                } else {
                    getAwardVO.setAwards(new ArrayList<>());
                }
                if (log.isInfoEnabled()) {
                    log.info("[award] 列表查询奖励，转换前:{},转换后:{}", JSON.toJSONString(serviceResult.getData()), JSON.toJSONString(getAwardVO));
                }
                return XmResultJson.success(getAwardVO);
            } else {
                return XmResultJson.fail(serviceResult.getErrorData(), serviceResult.getMsg());
            }

        }
    }

    /**
     * 删除奖励
     *
     * @param id      奖励id
     * @param request 请求
     * @return 删除结果
     */
    @DeleteMapping(value = "/award")
    public XmResultJson<DeleteAwardVO> deleteAward(@RequestParam(value = "id") String id, HttpServletRequest request) {
        DeleteAwardParam deleteAwardParam = new DeleteAwardParam();
        deleteAwardParam.setId(id);
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(deleteAwardParam);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST, violation.getMessage());
        }

        // token获取orgId

        String orgId = SecurityContextHolder.getOrgId();
        if (log.isInfoEnabled()) {
            log.info("[award] 从token里获取orgId:{}", orgId);
        }
        DeleteAwardDTO serviceParam = new DeleteAwardDTO();
        serviceParam.setAwardId(deleteAwardParam.getId());
        serviceParam.setOrgId(orgId);
        if (log.isInfoEnabled()) {
            log.info("[award] 删除奖励请求参数:{}", JSON.toJSONString(serviceParam));
        }
        ServiceResult<Integer> result = awardAwardService.deleteAward(serviceParam);
        if (result.isSuccess()) {
            DeleteAwardVO deleteAwardVO = new DeleteAwardVO();
            deleteAwardVO.setCount(result.getData());
            return XmResultJson.success(deleteAwardVO);
        } else {
            return XmResultJson.fail(result.getErrorData(), result.getMsg());
        }
    }

    /**
     * 修改奖励状态
     *
     * @param updateAwardStatusParam 修改奖励状态入参
     * @param request                请求
     * @return 修改奖励状态结果
     */
    @PutMapping(value = "/award/status")
    public XmResultJson<UpdateAwardStatusVO> updateAwardStatus(@RequestBody UpdateAwardStatusParam updateAwardStatusParam, HttpServletRequest request) {
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(updateAwardStatusParam);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST, violation.getMessage());
        }
        // token获取orgId

        String orgId = SecurityContextHolder.getOrgId();
        if (log.isInfoEnabled()) {
            log.info("[award] 从token里获取orgId:{}", orgId);
        }

        // 获取用户id和name

        TokenDTO tokenDTO = SecurityContextHolder.getToken();
        String userId = tokenDTO.getUserId();
        String userName = tokenDTO.getRealName();
        if (log.isInfoEnabled()) {
            log.info("[award] 用户token信息:{}", JSON.toJSONString(tokenDTO));
        }
        UpdateAwardStatusDTO serviceParam = new UpdateAwardStatusDTO();
        serviceParam.setOrgId(orgId);
        serviceParam.setAwardId(updateAwardStatusParam.getId());
        serviceParam.setStatus(updateAwardStatusParam.getStatus());
        serviceParam.setUserId(userId);
        serviceParam.setUserName(userName);
        if (log.isInfoEnabled()) {
            log.info("[award] 更新奖励状态入参{}", JSON.toJSONString(serviceParam));
        }
        ServiceResult<String> result = awardAwardService.updateAwardStatus(serviceParam);
        if (result.isSuccess()) {
            UpdateAwardStatusVO updateAwardStatusVO = new UpdateAwardStatusVO();
            updateAwardStatusVO.setMsg("Success");
            return XmResultJson.success(updateAwardStatusVO);
        } else {
            return XmResultJson.fail(result.getErrorData(), result.getMsg());
        }
    }

    /**
     * 奖励请求统计
     *
     * @param awardId   奖励id
     * @param deliverId 投放id
     * @param request   请求
     * @return 统计结果
     */
    @GetMapping(value = "/award/req")
    public XmResultJson<GetRequestStatsVO> getRequestStats(@RequestParam(value = "award_id") String awardId,
                                                           @RequestParam(value = "deliver_id", required = false) String deliverId, HttpServletRequest request) {
        if (StrUtil.isEmpty(awardId)) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST, "奖励id异常！");
        }
        // token获取orgId

        String orgId = SecurityContextHolder.getOrgId();
        if (log.isInfoEnabled()) {
            log.info("[award] 从token里获取orgId:{}", orgId);
        }

        // 调用服务接口
        com.bestcem.xm.award.grpc.service.param.award.GetRequestStatsParam serviceParam = new com.bestcem.xm.award.grpc.service.param.award.GetRequestStatsParam();
        serviceParam.setOrgId(orgId);
        serviceParam.setAwardId(awardId);
        serviceParam.setDeliverId(deliverId);
        if (log.isInfoEnabled()) {
            log.info("[award] 奖励请求统计入参{}", JSON.toJSONString(serviceParam));
        }
        ServiceResult<GetRequestStatsDTO> result = awardAwardService.getRequestStats(serviceParam);
        if (result.isSuccess()) {
            GetRequestStatsVO getRequestStatsVO = new GetRequestStatsVO();
            getRequestStatsVO.setTotal(result.getData().getTotalCount());
            getRequestStatsVO.setPass(result.getData().getPassCount());
            return XmResultJson.success(getRequestStatsVO);
        } else {
            return XmResultJson.fail(result.getErrorData(), result.getMsg());
        }
    }

    /**
     * 获取奖项等级、奖项名称
     *
     * @param awardId    奖励id
     * @param queryLevel 查询等级
     * @param queryName  查询名称
     * @param request    请求
     * @return 奖项等级、奖项名称
     */
    @GetMapping(value = "/award/draw/code/filter")
    public XmResultJson<ListAwardLevelNamesVO> listAwardLevelNames(@RequestParam(value = "award_id") String awardId,
                                                                   @RequestParam(value = "query_level", required = false) Boolean queryLevel,
                                                                   @RequestParam(value = "query_name", required = false) Boolean queryName, HttpServletRequest request) {

        ListAwardLevelNamesParam listAwardLevelNamesParam = new ListAwardLevelNamesParam();
        listAwardLevelNamesParam.setAwardId(awardId);
        listAwardLevelNamesParam.setQueryLevel(Objects.isNull(queryLevel) ? false : queryLevel);
        listAwardLevelNamesParam.setQueryName(Objects.isNull(queryName) ? false : queryName);
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(listAwardLevelNamesParam);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST, violation.getMessage());
        }
        // token获取orgId

        String orgId = SecurityContextHolder.getOrgId();
        if (log.isInfoEnabled()) {
            log.info("[award] 从token里获取orgId:{}", orgId);
        }
        ListAwardsLevelNamesParam serviceParam = new ListAwardsLevelNamesParam();
        serviceParam.setOrgId(orgId);
        serviceParam.setAwardId(listAwardLevelNamesParam.getAwardId());
        serviceParam.setQueryLevel(listAwardLevelNamesParam.getQueryLevel());
        serviceParam.setQueryName(listAwardLevelNamesParam.getQueryName());
        if (log.isInfoEnabled()) {
            log.info("[award] 获取奖项等级、奖项名称入参{}", JSON.toJSONString(serviceParam));
        }
        ServiceResult<AwardsDTO> result = awardAwardService.listAwardsLevelNames(serviceParam);
        if (result.isSuccess()) {
            ListAwardLevelNamesVO listAwardLevelNamesVO = new ListAwardLevelNamesVO();
            AwardsDTO data = result.getData();
            listAwardLevelNamesVO.setLevels(data.getLevel());
            listAwardLevelNamesVO.setNames(data.getName());
            if (log.isInfoEnabled()) {
                log.info("[award] 获取奖项等级、奖项名称返回数据:{}", JSON.toJSONString(listAwardLevelNamesVO));
            }
            return XmResultJson.success(listAwardLevelNamesVO);
        } else {
            return XmResultJson.fail(result.getErrorData(), result.getMsg());
        }
    }

    /**
     * 最近一周奖励请求统计
     *
     * @param awardId 奖励id
     * @param request 请求
     * @return 最近一周奖励请求统计
     */
    @GetMapping(value = "/award/weekReq")
    public XmResultJson<GetWeekRequestStatsVO> getWeekRequestStats(@RequestParam(value = "award_id") String awardId, HttpServletRequest request) {
        if (StrUtil.isEmpty(awardId)) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST, "奖励id异常！");
        }
        GetWeekRequestStatsParam getWeekRequestStatsParam = new GetWeekRequestStatsParam();
        getWeekRequestStatsParam.setAwardId(awardId);
        // token获取orgId

        String orgId = SecurityContextHolder.getOrgId();
        if (log.isInfoEnabled()) {
            log.info("[award] 从token里获取orgId:{}", orgId);
        }
        getWeekRequestStatsParam.setOrgId(orgId);
        if (log.isInfoEnabled()) {
            log.info("[award] 最近一周奖励请求统计请求参数:{}", JSON.toJSONString(getWeekRequestStatsParam));
        }
        ServiceResult<GetWeekRequestStatsVO> result = awardAwardService.getWeekRequestStats(getWeekRequestStatsParam);
        if (result.isSuccess()) {
            if (log.isInfoEnabled()) {
                log.info("[award] 最近一周奖励请求统计返回数据:{}", JSON.toJSONString(result.getData()));
            }
            return XmResultJson.success(result.getData());
        } else {
            return XmResultJson.fail(result.getErrorData(), result.getMsg());
        }
    }

    /**
     * 补跑定时任务
     *
     * @param requestStatsDayParam
     * @return
     */
    @PostMapping(value = "/award/requestStatsDayJob")
    public XmResultJson<String> requestStatsDayJob(@RequestBody RequestStatsDayParam requestStatsDayParam) {
        if (CollectionUtils.isEmpty(requestStatsDayParam.getDays())) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST, "日期缺失！");
        }
        Set<DateTime> dateSet = requestStatsDayParam.getDays().stream().map(day -> DateUtil.parse(day, DatePattern.NORM_DATE_FORMAT)).collect(Collectors.toSet());

        new Thread() {
            @Override
            public void run() {
                for (Date date : dateSet) {
                    try {
                        ServiceResult<String> result = awardStatsService.dailyRequestStats(date);
                        if (!result.isSuccess()) {
                            log.error("[award] 奖励统计定时任务补跑失败:{},{}", DateUtil.formatDate(date), result.getMsg());
                        }
                    } catch (Exception e) {
                        log.error("[award] 奖励统计定时任务补跑异常:" + DateUtil.formatDate(date), e);
                    }

                }
            }
        }.start();

        return XmResultJson.success();
    }

//    @Resource
//    private RabbitMqMessageSender rabbitMqMessageSender;

    /**
     * 补发延迟消息
     *
     * @param param ReissueDelayMsgParam
     * @return success
     */
//    @AuthIgnore
//    @PostMapping(value = "/award/reissueDelayMsg")
//    public XmResultJson<String> reissueDelayMsg(@RequestBody ReissueDelayMsgParam param) {
//        rabbitMqMessageSender.mqSendJob(param.getStartDelayTime(), param.getStartDelayTime());
//        return XmResultJson.success();
//    }
}
